"""
Nice simple cherrypy example of ajax with json in and out.
"""

import cherrypy, os
from minimarkup import P, Q

class View(P):
    def __init__(self, title=None, scripts=None):
        P.__init__(self, '<!DOCTYPE html>')
        self.html( )
        self.head( )
        self.meta( charset='utf-8').noclose()
        if title:
            self.title( title )
        if scripts:
            for script in scripts:
                self.script(src=script).close()
        self.head.close()
        self.body()

    def render(self):
        self.body.close()
        self.html.close()
        return self()

class Controller(object):

    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def ajax(self):
        json = cherrypy.request.json
        print json
        return dict(result='False' if json['value']=='True' else 'True')

    @cherrypy.expose
    def index(self):
        v = View('index', ['//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', 'static/main.js'])
        v.table(border=True)
        v.tr(Q.td(Q.input(type='button', name='i1', value='True',  onclick='callAjax(this)')))
        v.tr(Q.td(Q.input(type='button', name='i2', value='False', onclick='callAjax(this)')))
        v.table.close()
        return v.render()

config = {'/static':{'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(os.path.abspath('.'), 'static')}}

cherrypy.quickstart(Controller(), config=config)
